﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Business;
using mojoPortal.Net;
using mojoPortal.Web.Framework;
using Resources;
using log4net;
using mojoPortal.Web;
using ud_ContactForm.Business;
using ud_Utilities;

namespace ud_ContactForm
{
	
	public partial class ContactForm : SiteModuleControl
	{
        private static readonly ILog log = LogManager.GetLogger(typeof(ContactForm));
        private ContactFormConfiguration config = new ContactFormConfiguration();
        
        protected override void OnInit(EventArgs e)
        {            
            base.OnInit(e);
            Load += Page_Load;
            btnSend.Click += btnSend_Click;
            LoadSettings();
            PopulateLabels();
            if (!config.UseSpamBlocking)
            {
                captcha.Enabled = false;
                captcha.Visible = false;
                divCaptcha.Visible = false;
            }
            else
            {
                captcha.ProviderName = siteSettings.CaptchaProvider;
                captcha.Captcha.ControlID = "captcha" + ModuleId;
                captcha.RecaptchaPrivateKey = siteSettings.RecaptchaPrivateKey;
                captcha.RecaptchaPublicKey = siteSettings.RecaptchaPublicKey;
            }
        }

        
        protected void Page_Load(object sender, EventArgs e)
		{
            Page.EnableViewState = true;
            
            BindToList();
            PopulateControls();
		}

	    private void PopulateControls()
        {
            pnlContainer.ModuleId = ModuleId;

            if (!Page.IsPostBack)
            {
                if (Request.IsAuthenticated)
                {
                    SiteUser siteUser = SiteUtils.GetCurrentSiteUser();
                    if (siteUser != null)
                    {
                        txtEmail.Text = siteUser.Email;
                        txtName.Text = siteUser.Name;
                    }
                }
                

            }
        }


        private void btnSend_Click(object sender, EventArgs e)
        {
            //Page.Validate("Contact");
            bool isValid = true;
            reqEmail.Validate();
            if (!reqEmail.IsValid) { isValid = false; }
            regexEmail.Validate();
            if (!regexEmail.IsValid) { isValid = false; }

            if ((isValid) && (txtMessage.Text.Length > 0))
            {
                if ((config.UseSpamBlocking) && (divCaptcha.Visible))
                {
                    if (!captcha.IsValid)
                    {
                        ScriptManager.RegisterClientScriptBlock(Page,
                            Page.GetType(), "reloadCaptcha",
                            "Recaptcha.reload();", true);
                        updatePanelMessage.Update();
                        return;
                    }
                }

                string subjectPrefix = config.SubjectPrefix;
                if (subjectPrefix.Length == 0)
                {
                    subjectPrefix = siteSettings.SiteName;
                }

                StringBuilder message = new StringBuilder();
                if (txtName.Text.Trim() != string.Empty)
                {
                    message.Append(ContactFormResources.ContactFormYourNameLabel + ": ");
                    message.Append("<strong>" + txtName.Text.Trim() + "</strong><br />");
                }
                if (txtSubject.Text.Trim() != string.Empty)
                {
                    message.Append(ContactFormResources.ContactFormSubjectLabel + ": ");
                    message.Append("<strong>" + txtSubject.Text.Trim() + "</strong><br />");
                }
                if (txtEmail.Text.Trim() != string.Empty)
                {
                    message.Append(ContactFormResources.ContactFormYourEmailLabel + ": ");
                    message.Append("<strong><a href='" + txtEmail.Text.Trim() + "' >" + txtEmail.Text.Trim() + "</a></strong><br />");
                }
                message.Append(txtMessage.Text + "<br /><br />");
                if (config.AppendIPToMessageSetting)
                {
                    message.Append("HTTP_USER_AGENT: " + Page.Request.ServerVariables["HTTP_USER_AGENT"] + "<br />");
                    message.Append("REMOTE_HOST: " + Page.Request.ServerVariables["REMOTE_HOST"] + "<br />");
                    message.Append("REMOTE_ADDR: " + SiteUtils.GetIP4Address() + "<br />");
                    message.Append("LOCAL_ADDR: " + Page.Request.ServerVariables["LOCAL_ADDR"] + "<br />");

                }

                Module m = new Module(ModuleId);
                if ((config.KeepMessages) &&(m.ModuleGuid != Guid.Empty))
                {
                    ContactFormMessage contact = new ContactFormMessage
                                                     {
                                                         ModuleGuid = m.ModuleGuid,
                                                         SiteGuid = siteSettings.SiteGuid,
                                                         Message = message.ToString()
                                                     };
                    if (config.SubjectPrefix.Trim() != string.Empty)
                    {
                        contact.Subject = config.SubjectPrefix + ": " + txtSubject.Text;
                    }
                    else
                    {
                        contact.Subject = txtSubject.Text;
                    }
                    contact.UserName = txtName.Text;
                    contact.Email = txtEmail.Text;
                    contact.CreatedFromIpAddress = SiteUtils.GetIP4Address();

                    if (Request.IsAuthenticated)
                    {
                        SiteUser currentUser = SiteUtils.GetCurrentSiteUser();
                        if (currentUser != null)
                            contact.UserGuid = currentUser.UserGuid;

                    }

                    contact.Save();


                }

                string fromAddress = siteSettings.DefaultEmailFromAddress;
                if (config.UseInputAsFromAddress) { fromAddress = txtEmail.Text; }

                if (config.EmailAddresses != null)
                {
                    SmtpSettings smtpSettings = SiteUtils.GetSmtpSettings();

                    if ((pnlToAddresses.Visible) && (ddToAddresses.SelectedIndex > -1))
                    {
                        string to = config.EmailAddresses[ddToAddresses.SelectedIndex];
                        try
                        {
                            Email.SendEmail(
                                smtpSettings,
                                fromAddress,
                                txtEmail.Text,
                                to,
                                string.Empty,
                                config.EmailBccAddresses,
                                subjectPrefix + ": " + txtSubject.Text,
                                message.ToString(),
                                true,
                                "Normal");

                        }
                        catch (Exception ex)
                        {
                            log.Error("error sending email from address was " + fromAddress + " to address was " + to, ex);
                        }

                    }
                    else
                    {

                        foreach (string to in config.EmailAddresses)
                        {
                            try
                            {
                                Email.SendEmail(
                                    smtpSettings,
                                    fromAddress,
                                    txtEmail.Text,
                                    to,
                                    string.Empty,
                                    config.EmailBccAddresses,
                                    subjectPrefix + ": " + txtSubject.Text,
                                    message.ToString(),
                                    true,
                                    "Normal");

                            }
                            catch (Exception ex)
                            {
                                log.Error("error sending email from address was " + fromAddress + " to address was " + to, ex);
                            }

                        }
                    }


                }


                lblMessage.Text = ContactFormResources.ContactFormThankYouLabel;
                pnlSend.Visible = false;
                WebUtils.SetupRedirect(this, SiteRoot + "/ContactForm/Finish.aspx?pageid=" + PageId.ToInvariantString() + "&mid=" + ModuleId.ToInvariantString());
            }
            else
            {
                lblMessage.Text = txtMessage.Text.Length == 0 ? ContactFormResources.ContactFormEmptyMessageWarning : "invalid";

            }

            btnSend.Text = ContactFormResources.ContactFormSendButtonLabel;
            btnSend.Enabled = true;

            ScriptManager.RegisterClientScriptBlock(Page,
        Page.GetType(), "reloadCaptcha",
            "Recaptcha.reload();", true);
            updatePanelMessage.Update();
        }

        

        private void PopulateLabels()
        {
            btnSend.Text = ContactFormResources.ContactFormSendButtonLabel;
            SiteUtils.SetButtonAccessKey(btnSend, ContactFormResources.ContactFormSendButtonAccessKey);
            txtMessage.Height = Unit.Parse(config.EditorHeight);
            Image imgProgress = upProgress1.FindControl("imgProgress") as Image;
            if (imgProgress != null)
            {
                imgProgress.ImageUrl = ImageSiteRoot + "/Data/Icon16x16/updateprogress.gif";
                imgProgress.AlternateText = ContactFormResources.Loading;
            }
            lblMessageLabel.Text = ContactFormResources.ContactFormMessageLabel;
            lblSubject.Text = ContactFormResources.ContactFormSubjectLabel;
            lblName.Text = ContactFormResources.ContactFormYourNameLabel;
            lblEmail.Text = ContactFormResources.ContactFormYourEmailLabel;
            if (config.UseRequireEmailSetting)
            {
                lblEmail.Text += @" " + ContactFormResources.RequireLabel;
            }
            if (config.UseRequireMesageSetting)
            {
                lblMessageLabel.Text += @" " + ContactFormResources.RequireLabel;
            }
            if (config.UseRequireNameSetting)
            {
                lblName.Text += @" " + ContactFormResources.RequireLabel;
            }
            if (config.UseRequireSubjectSetting)
            {
                lblSubject.Text += @" " + ContactFormResources.RequireLabel;
            }
            
            reqEmail.ErrorMessage = ContactFormResources.ContactFormValidAddressLabel;
            regexEmail.ErrorMessage = ContactFormResources.ContactFormValidAddressLabel;

            Title1.Visible = !RenderInWebPartMode;
            if (ModuleConfiguration != null)
            {
                Title = Utilities.RemoveTwoColorModuleTitleText(ModuleConfiguration.ModuleTitle);
                Description = ModuleConfiguration.FeatureName;
            }

            Title1.EditUrl = string.Empty;
            Title1.EditText = string.Empty;
            Title1.ToolTip = string.Empty;
            if (IsEditable)
            {
                mojoBasePage basePage = Page as mojoBasePage;
                if (basePage != null)
                {
                    basePage.ScriptConfig.IncludeGreyBox = true;
                    if (config.KeepMessages)
                    {
                        Title1.LiteralExtraMarkup =
                                "&nbsp;<a href='"
                                + SiteRoot
                                + "/ContactForm/MessageListDialog.aspx?pageid=" + PageId.ToInvariantString()
                                + "&amp;mid=" + ModuleId.ToInvariantString()
                                + "' class='ModuleEditLink' title='" + ContactFormResources.ContactFormViewMessagesLink + "' "
                                + "onclick='GB_showFullScreen(title, href); return false;'"
                                + "><img src='/Data/Icon16x16/Text.png' alt='" + ContactFormResources.ContactFormViewMessagesLink + "'</img></a>";
                    }
                }
            }

        }

        private void BindToList()
        {
            if (Page.IsPostBack) { return; }
            if (!pnlToAddresses.Visible) { return; }
            if (config.EmailAddresses == null) { return; }
            if (config.EmailAddresses.Count <= 1) { return; }
            

            List<string> bindList = new List<string>();
            int index = 0;
            foreach (string a in config.EmailAddresses)
            {
                bindList.Add((index + 1) <= config.EmailAliases.Count ? config.EmailAliases[index] : a);
                index += 1;
            }

            index = 0;
            foreach (string a in bindList)
            {
                ListItem item = new ListItem(a, index.ToInvariantString());
                ddToAddresses.Items.Add(item);
                index += 1;
            }

        }


        private void LoadSettings()
        {
            config = new ContactFormConfiguration(Settings);
            Page.Form.Action = SiteUtils.GetCurrentPageUrl();
            if (config.InstanceCssClass.Length > 0) { pnlContainer.CssClass += " " + config.InstanceCssClass; }

            if ((config.EmailAddresses != null) && (config.EmailAddresses.Count > 1))
            {
                pnlToAddresses.Visible = true;
                
            }

            //if (ScriptController != null)
            //{
            //    ScriptController.RegisterAsyncPostBackControl(btnSend);
            //}
            btnSend.ValidationGroup = "Contact" + ModuleId.ToInvariantString();
            if (config.UseRequireEmailSetting)
            {
                reqEmail.ValidationGroup = "Contact" + ModuleId.ToInvariantString();
                regexEmail.ValidationGroup = "Contact" + ModuleId.ToInvariantString();
            }
            if (config.UseRequireMesageSetting)
            {
                reqMessage.ValidationGroup = "Contact" + ModuleId.ToInvariantString();
            }
            if (config.UseRequireNameSetting)
            {
                reqName.ValidationGroup = "Contact" + ModuleId.ToInvariantString();
            }
            if (config.UseRequireSubjectSetting)
            {
                reqSubject.ValidationGroup = "Contact" + ModuleId.ToInvariantString();
            }
        }
    }
}
